package com.leador.service;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.text.TextUtils;
import android.util.Log;

import com.leador.assist.DataQueueManager;
import com.leador.assist.LBSServiceHandler;
import com.leador.broadcase.NetBroadCastReceiver;
import com.leador.core.KernelRunnable;
import com.leador.core.KernelThread;
import com.leador.core.Trace;
import com.leador.db.DBManger;
import com.leador.db.SyncDBManager;
import com.leador.location.LocateHelper;
import com.leador.manger.LBSTraceClient;
import com.leador.module.AppInfo;
import com.leador.socket.SocketMananger;
import com.leador.utils.ServiceState;
import com.leador.utils.SharedPreferUtils;
import com.leador.utils.TraceSeleGenre;
import com.leador.utils.Utils;

import java.util.HashMap;

/**
 * Created by lhy on 2016/9/11.
 */
public class LBSTraceService  extends Service{
    private final LBSServiceHandler lbsServiceHandler = new LBSServiceHandler(this);
    private Messenger messenger = new Messenger(lbsServiceHandler);
    private Messenger UIMessenger = null;
    private SharedPreferUtils sharedPreferUtils;
    private  Context context;
    private  AppInfo appInfo;
    public static ServiceState serviceState = ServiceState.NOT_START;
    private KernelThread kernelThread;
    private KernelRunnable kernelRunnable;
    private LocateHelper locateHelper;
    private SocketMananger socketManager = null;
    private NetBroadCastReceiver netBroadCastReceiver = new NetBroadCastReceiver(this);
    private DBManger dbManger;
    private DataQueueManager dataQueueManager;
    private  boolean isRegisterReceiver = false;
    public   boolean isRestart = true;
    public static final Object dbLock = new Object();
    public  boolean syncHttpFlag = true;
    public LBSTraceService(){
        dataQueueManager = DataQueueManager.getInstance();
    }

    @Override
    public IBinder onBind(Intent intent) {
        return this.messenger.getBinder();
    }

    @Override
    public void onCreate() {
        super.onCreate();
        context = getApplicationContext();
        sharedPreferUtils = SharedPreferUtils.getInstance(context);
    }

    @Override
    public  boolean onUnbind(Intent paramIntent) {
        return super.onUnbind(paramIntent);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if(socketManager != null && ServiceState.LOGOUTING != serviceState){
            socketManager.disSocketConnect();
        }
        if (isRegisterReceiver) {
            unregisterReceiver(this.netBroadCastReceiver);
            isRegisterReceiver = false;
        }
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.e("onStartCommand","onStartCommand");
        Bundle bundle = null;
        int hasEntity = 0;
        if (intent != null) {
            String entityName = "";
            long serviceId = 0L;
            bundle = intent.getBundleExtra("initData");
            if (bundle != null) {
                String key = "";
                if (bundle.containsKey("ak")) {
                    key = bundle.getString("ak");
                }
                if (bundle.containsKey("serviceId")) {
                    serviceId = bundle.getLong("serviceId");
                }
                if (bundle.containsKey("entityName")) {
                    entityName = bundle.getString("entityName");
                }
                String mcode = "";
                if (bundle.containsKey("mcode")) {
                    mcode = bundle.getString("mcode");
                }
                String pcn = "";
                if (bundle.containsKey("pcn")) {
                    pcn = bundle.getString("pcn");
                }
                appInfo = new AppInfo(this);
                appInfo.setKey(key);
                appInfo.setServiceId(serviceId);
                appInfo.setEntityName(entityName);
                appInfo.setCode(mcode);
                appInfo.setPcn(pcn);
                saveLocateCache(appInfo);
            }
            hasEntity = (!appInfo.entityName.equals(entityName)) || (serviceId != appInfo.serviceId) ? 1 : 0;
        }else {
            try {
                appInfo = new AppInfo(this);
                if (sharedPreferUtils == null) {
                    //获取本地缓存文件
                    sharedPreferUtils = SharedPreferUtils.getInstance(context);
                }
                String client = this.sharedPreferUtils.getMap("client");
                HashMap map = client != null ? getCacheMap(client) : null;
                if ((map != null) && (map.size() >= 7)) {
                    String key = (String) map.get("ak");
                    long serviceId = Long.parseLong((String) map.get("serviceId"));
                    String entityName = (String) map.get("entityName");
                    String code = (String) map.get("mcode");
                    String pcn = (String) map.get("pcn");
                    String md = (String) map.get("md");
                    String cpu = (String) map.get("cpu");
                    appInfo.setKey(key);
                    appInfo.setEntityName(entityName);
                    appInfo.setCode(code);
                    appInfo.setPcn(pcn);
                    appInfo.setMd(md);
                    appInfo.setServiceId(serviceId);
                    appInfo.setCpu(cpu);
                }
            } catch (Exception localException1) {

            }
        }
//            //获取手机信息
//            AppInfo.getAppInfo(this);
//            TraceJniInterface.setAppInfo(AppInfo.key, AppInfo.entityName, String.valueOf(AppInfo.serviceId));
//            TraceJniInterface.setDeviceInfo(AppInfo.deviceid, AppInfo.teleDeviId, AppInfo.simSerialNumber, AppInfo.androidVersion
//                    , AppInfo.appVersion, AppInfo.deviIdImei, AppInfo.md, AppInfo.cpu);
                Log.e("serviceState",ServiceState.LOGGING+"");
                initHttpOrSocket();
                boolean hasNetWork = Utils.isNetworkConnected(this);
                if(!hasNetWork){
                    //无网络
                    netUnAvailable();
                }else if(hasEntity != 0){
                    serviceState = ServiceState.LOGGING;
                    startHttpOrSocket();
                }else if(ServiceState.LOGGING == serviceState){
                    //服务器正在开启
                    Message message = lbsServiceHandler.obtainMessage(22);
                    sendHandlerMessage(message);
                }else if(ServiceState.LOGOUTING == serviceState){
                    //服务器停止
                    Message message = lbsServiceHandler.obtainMessage(181);
                    sendHandlerMessage(message);
                }else if(ServiceState.NOT_START == serviceState){
                    serviceState = ServiceState.LOGGING;
                    startHttpOrSocket();
                }else if(ServiceState.BUFFER == serviceState){
                    Message message = lbsServiceHandler.obtainMessage(21);
                    sendHandlerMessage(message);
                }else{
                    Message message = lbsServiceHandler.obtainMessage(25);
                    sendHandlerMessage(message);
                }
        return 1;
    }

    private boolean sendMessage(Message message) {
        try {
            if (this.UIMessenger != null) {
                this.UIMessenger.send(message);
                return true;
            }
        } catch (Exception localException) {
        }
        return false;
    }

    /**
     * 发送消息
     * @param message
     * @return
     */
    public boolean sendHandlerMessage(Message message){
        if(message == null){
           return false;
        }
        try {
            UIMessenger.send(message);
            return true;
        } catch (RemoteException e1) {
            e1.printStackTrace();
        }
        return  false;
    }

    /**
     * 初始化 http 或者 socket
     */
    private void initHttpOrSocket(){
        if(ServiceState.NOT_START != serviceState){
            return;
        }
        Log.e("initHttpOrSocket","initHttpOrSocket");
        //1.http请求
        if(TraceSeleGenre.DATA_HHTP.getValue() == Trace.traceType){
            initHttp();
        }

        //2.socket建立连接（1.上传数据 2.不上传但是接受回调用于监控）
        if(TraceSeleGenre.DATA_SOCKET.getValue() == Trace.traceType || TraceSeleGenre.NOT_DATA_SOCKET_CONNECT.getValue() == Trace.traceType){
            initSocket();
        }
    }

    private void startHttpOrSocket(){
        //1.http请求
        if(TraceSeleGenre.DATA_HHTP.getValue() == Trace.traceType){
            serviceState = ServiceState.STARTED;
            startHttp();
        }

        //2.socket建立连接（1.上传数据 2.不上传但是接受回调用于监控）
        if(TraceSeleGenre.DATA_SOCKET.getValue() == Trace.traceType || TraceSeleGenre.NOT_DATA_SOCKET_CONNECT.getValue() == Trace.traceType){
            serviceState = ServiceState.LOGGING;
            startSocket();
        }
    }

    private void initHttp(){
        if(kernelThread!=null){
            if(kernelThread.isCache){
                return;
            }

            if(kernelThread.isLogin && locateHelper != null){
                kernelThread.setLgoinCacheEable(true,false);
            }
        }

        if(locateHelper == null){
            locateHelper = new LocateHelper(this);
        }

        initKernelThread(true,false);
    }

    public void startHttp(){
        if(LBSTraceClient.onStartTraceListener != null){
            LBSTraceClient.onStartTraceListener.onTraceCallback(100,"sucess");
        }
    }

    public void initSocket(){
        if(kernelThread != null){
            if(kernelThread.isLogin && locateHelper != null){
                kernelThread.setLgoinCacheEable(true,false);
                return;
            }
        }

        if(locateHelper == null){
            locateHelper = new LocateHelper(this);
        }
        initKernelThread(true,false);
    }

    private void startSocket(){
        if(socketManager == null){
            socketManager = SocketMananger.getInstance(this);
        }
        socketManager.disSocketConnect();
        socketManager.startSocketConnect();
    }

    /**
     * 初始化循环线程
     * @param isLogin
     * @param isCache
     */
    private void initKernelThread(boolean isLogin,boolean isCache){
        //clear thread
        if(kernelThread != null){
            Handler handler = kernelThread.getHandler();
            if(kernelRunnable!=null && handler!=null){
                handler.removeCallbacks(kernelRunnable);
            }
            kernelRunnable = null;
            kernelThread = null;
        }

        kernelThread = new KernelThread(this,isLogin,isCache);

        //服务使用标识
        kernelThread.serverEnable = true;

        //发包周期(过滤作用)
        int packInterval = Trace.getPackInterval();
        if (packInterval >= 2) {// 发包必须大于2s,默认30s
            kernelThread.setPackIntervalTime(packInterval*1000);
        }

        //采点周期
        int gahterInterval = Trace.getGatherInterval();
        if(gahterInterval > 2){
            locateHelper.setGatherInterval(Trace.getGatherInterval() * 1000);
        }

        //距离周期
        int distanceInterval = Trace.getDistanceInterval();
        if(distanceInterval > 2){
            locateHelper.setDistanceInterval(distanceInterval);
        }

        //设置采点周期
        kernelThread.resetInterval();
        kernelThread.start();
    }

    /**
     * 断开socket连接
     */
    public  void socketDisconnet() {
        sendCacheMessage();
        if (this.socketManager == null) {
            this.socketManager = SocketMananger.getInstance(this);
        }
        this.socketManager.disSocketConnect();
        clearLocationCache();
    }

    /**
     * 无网络情况下 停止服务 开启缓存
     */
    public  void netUnAvailable() {
        Log.e("netUnAvailable","netUnAvailable");
        if (ServiceState.LOGOUTING == serviceState) {
            stopService();
            return;
        }
        reInit();
        setCacheProperty();
        sendCacheMessage();
    }

    /**
     * 重新初始化
     */
    public void reInit(){
        if(kernelThread == null){
            return;
        }

        if(kernelThread.isCache){
            return;
        }
        if(kernelThread.isLogin && locateHelper!=null){
            kernelThread.setLgoinCacheEable(true,false);
        }
        if(kernelThread == null){
            initKernelThread(true,false);
        }
    }

    /**
     * 设置缓存标识属性
     */
    private void setCacheProperty() {
        if(kernelThread == null){
            return;
        }
        if(!kernelThread.isCache) {
            if(kernelThread.isLogin ) {
                kernelThread.setLoginCaheEable(true, true);
            } else {
                if(TraceSeleGenre.DATA_SOCKET.getValue() == Trace.traceType
                        || TraceSeleGenre.DATA_HHTP.getValue() == Trace.traceType ) {
                    kernelThread.setLoginCaheEable(true, true);
                }
            }
        }
    }

    /**
     * 缓存开启
     */
    public void sendCacheMessage(){
        Object localObject;
        if (TraceSeleGenre.NOT_DATA_SOCKET_CONNECT.getValue() == Trace.traceType) {
            localObject = lbsServiceHandler.obtainMessage(19);
            if ((!sendMessage((Message)localObject)) && (LBSTraceClient.onStartTraceListener != null)) {
                try {
                    LBSTraceClient.onStartTraceListener.onTraceCallback(10004, "网络未开启");
                }
                catch (Exception localException1) {}
            }
            serviceState = ServiceState.NOT_START;
            kernelRunnable = null;
        }
        else if (TraceSeleGenre.DATA_SOCKET.getValue() == Trace.traceType || TraceSeleGenre.DATA_HHTP.getValue() == Trace.traceType) {
            if (ServiceState.BUFFER == serviceState) {
                localObject = lbsServiceHandler.obtainMessage(21);
                if ((!sendMessage((Message)localObject)) && (LBSTraceClient.onStartTraceListener != null)) {
                    try {
                        LBSTraceClient.onStartTraceListener.onTraceCallback(10009, "已开启缓存");
                    }
                    catch (Exception localException2) {

                    }
                }
            } else {
                localObject = lbsServiceHandler.obtainMessage(20);
                if ((!sendMessage((Message)localObject)) && (LBSTraceClient.onStartTraceListener != null)) {
                    try {
                        LBSTraceClient.onStartTraceListener.onTraceCallback(10008, "开启缓存");
                    } catch (Exception localException3) {

                    }
                }
                serviceState = ServiceState.BUFFER;
            }
        } else{
            return;
        }

        if (isRegisterReceiver) {
            return;
        }
        IntentFilter filter = new IntentFilter();
        filter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
        registerReceiver(this.netBroadCastReceiver, filter);
        isRegisterReceiver = true;
    }

    /**
     * 停止服务
     */
    public final void stopService() {
        clearLocationCache();
        if (isRegisterReceiver) {
            unregisterReceiver(this.netBroadCastReceiver);
            isRegisterReceiver = false;
        }
        serviceState = ServiceState.NOT_START;
        if(kernelThread != null){
            if(kernelThread.getQueSize()>0){
                new SyncDBManager(this).start();
            }
            kernelThread.release();
            if(kernelRunnable != null){
                kernelThread.getHandler().removeCallbacks(kernelRunnable);
            }
            kernelThread = null;
            kernelRunnable = null;
        }

        if(socketManager != null){
            socketManager.disSocketConnect();
        }

        if(locateHelper != null){
            locateHelper.removeUpdates();
            locateHelper = null;
        }

        isRestart = true;
        Message localMessage = lbsServiceHandler.obtainMessage(29);
        sendMessage(localMessage);
        stopSelf();
    }

    /**
     * 存入到本地
     */
    private void saveLocateCache(AppInfo appInfo) {
        clearLocationCache();
        String str = appInfo.key + "-|-" + appInfo.serviceId + "-|-" + appInfo.entityName + "-|-" + appInfo.code + "-|-" + appInfo.pcn + "-|-" + appInfo.md + "-|-" + appInfo.cpu;
        if (this.sharedPreferUtils == null) {
            this.sharedPreferUtils = SharedPreferUtils.getInstance(context);
        }
        try
        {
            this.sharedPreferUtils.putMap("client", str);
            this.sharedPreferUtils.setMapToShared();
            return;
        } catch (Exception e1) {
            return;
        }
    }

    /**
     *  清除本地缓存
     */
    protected final void clearLocationCache() {
        if (this.sharedPreferUtils == null) {
            this.sharedPreferUtils = SharedPreferUtils.getInstance(context);
        }
        try {
            this.sharedPreferUtils.putMap("client", null);
            this.sharedPreferUtils.setMapToShared();
            return;
        }
        catch (Exception localException) {}
    }

    /**
     * 获取缓存信息
     * @param str
     * @return
     */
    private  HashMap getCacheMap(String str) {
        String [] strarray;
        if (TextUtils.isEmpty(str)) {
            return null;
        }
        try {
            strarray = str.split("-\\|-");
        } catch (Exception localException) {
            return null;
        }
        if ((strarray != null) && (strarray.length >= 7)) {
            HashMap hashMap = new HashMap();
            hashMap.put("ak", strarray[0]);
            hashMap.put("serviceId", strarray[1]);
            hashMap.put("entityName", strarray[2]);
            hashMap.put("mcode", strarray[3]);
            hashMap.put("pcn", strarray[4]);
            hashMap.put("md", strarray[5]);
            hashMap.put("cpu", strarray[6]);
            return hashMap;
        }
        return null;
    }

    /**
     * 获取handler
     * @return
     */
    public LBSServiceHandler getLbsServiceHandler() {
        return lbsServiceHandler;
    }

    /**
     * 获取DB
     * @return
     */
    public DBManger getDbManger(){
        return dbManger;
    }

    /**
     * 获取上下文
     * @return
     */
    public Context getContext(){
        return context;
    }

    /**
     * 获取Location帮助类
     * @return
     */
    public LocateHelper getLocateHelper(){
        return locateHelper;
    }

    /**
     * 获取socketManager
     * @return
     */
    public SocketMananger getSocketManager(){
        return socketManager;
    }

    /**
     * 设置周期参数
     * @param message
     */
    public   void setIntervalMessage(Message message) {
        Bundle v0 = message.getData();
        int gatherInterval = v0.getInt("gatherInterval");
        int packInterval = v0.getInt("packInterval");
        int distanceInterval = v0.getInt("distanceInterval");
        if (gatherInterval >= locateHelper.baseGatherInterval) {
            locateHelper.gatherInterval = gatherInterval * 1000;
        }

        if (packInterval >= 2) {
            kernelThread.packIntervalTime = packInterval * 1000;
        }

        if(distanceInterval>=2){
            locateHelper.distanceInterval = distanceInterval;
        }

        kernelThread.resetInterval();
    }

    /**
     * 重启http
     */
    public void reStartHttpByNetConnect(boolean isCache){
        Log.e("reStartHttp","reStartHttpByNetConnect" + "," +serviceState);
        if ((ServiceState.LOGGING == serviceState) || (ServiceState.STARTED == serviceState)) {
            return;
        }
        serviceState = ServiceState.STARTED;
        if(kernelRunnable == null){
            initKernelThread(true,isCache);
        }else{
            kernelThread.setLoginCaheEable(true,isCache);
        }
    }

    /**
     * 重启socket
     */
    public final void reStartSocketByNetConnect() {
        if ((ServiceState.LOGGING == serviceState) || (ServiceState.STARTED == serviceState)) {
            return;
        }
        serviceState = ServiceState.LOGGING;
        initSocket();
        startSocket();
        Log.e("startSocket","socketSocke222");
    }

    //--------------------handler----------------------------------
    /**
     * socket连接时候启动成功
     */
    public void socketConnectSucess() {
        if (isRegisterReceiver) {
            //注销网络切换
            unregisterReceiver(netBroadCastReceiver);
            isRegisterReceiver = false;
        }

        startScoketService();
        serviceState = ServiceState.STARTED;

        if(isRestart){
            if ((LBSTraceClient.onStartTraceListener != null)) {
                try {
                    LBSTraceClient.onStartTraceListener.onTraceCallback(0, "sucess");
                }
                catch (Exception localException1) {
                }
            }
        }
    }

    public void reStartScocket(){
        if(socketManager == null){
            socketManager =  SocketMananger.getInstance(this);
        }
        socketManager.disSocketConnect();
        if(ServiceState.LOGOUTING == serviceState){
            this.socketManager = null;
            stopService();
            return;
        }
        initSocket();
        boolean hasNetWork = Utils.isNetworkConnected(this);
        if(hasNetWork){
            isRestart = false;
            serviceState = ServiceState.LOGGING;
            socketManager.startSocketConnect();
            return;
        }
        setCacheProperty();
        sendCacheMessage();
    }

    /**
     * http 缓存通知
     */
    public void setHttpCacheNotity(){
        sendCacheMessage();
        if(kernelThread == null){
            return;
        }
        kernelThread.isCache = true;
    }

    /**
     * http 缓存不通知
     */
    public void setHttpCacheAi(){
        serviceState = ServiceState.STARTED;
        if(kernelThread == null){
            return;
        }
        kernelThread.isCache = false;
    }

    /**
     * http停止
     */
    public void httpSotp() {
        Message localMessage;
        if (ServiceState.NOT_START == serviceState) {
            localMessage = lbsServiceHandler.obtainMessage(27);
            sendMessage(localMessage);
            return;
        }
//        if (ServiceState.LOGOUTING == serviceState) {
//            if (kernelThread != null) {
//                kernelThread.setLoginCaheEable(false, false);
//            }
//            localMessage = lbsServiceHandler.obtainMessage(28);
//            sendMessage(localMessage);
//            return;
//        }
//        serviceState = ServiceState.LOGOUTING;
        if (kernelThread != null) {
            kernelThread.setLoginCaheEable(false, false);
        }
        localMessage = lbsServiceHandler.obtainMessage(29);
        sendMessage(localMessage);
        serviceState = ServiceState.NOT_START;
    }

    public void stopTrack(){
        Message localMessage;
        if (ServiceState.NOT_START == serviceState) {
            localMessage = lbsServiceHandler.obtainMessage(27);
            sendMessage(localMessage);
            return;
        }
        if (ServiceState.LOGOUTING == serviceState) {
            if (kernelThread != null) {
                kernelThread.setLoginCaheEable(false, false);
            }
            localMessage = lbsServiceHandler.obtainMessage(28);
            sendMessage(localMessage);
            return;
        }
        serviceState = ServiceState.LOGOUTING;
        if (kernelThread != null) {
            kernelThread.setLoginCaheEable(false, false);
            kernelThread.setLogout(true);
            if ((!socketManager.socketConnect.socketIsConnect()) && (TraceSeleGenre.NOT_DATA_SOCKET_CONNECT.getValue() == Trace.traceType)) {
                stopService();
            }
            return;
        }
        serviceState = ServiceState.NOT_START;
    }

    protected final void startScoketService() {
        if (TraceSeleGenre.DATA_SOCKET.getValue() == Trace.traceType) {
            if (locateHelper == null) {
                locateHelper = new LocateHelper(this);
            }
            if (this.socketManager == null) {
                this.socketManager = SocketMananger.getInstance(this);
            }
            dbEnable = false;
            startDbThread();
            if (kernelThread != null) {
                kernelThread.setLoginCaheEable(true, false);
            } else {
                initKernelThread(true,false);
            }
        } else if (TraceSeleGenre.NOT_DATA_SOCKET_CONNECT.getValue() == Trace.traceType) {
            initKernelThread(true,false);
        }

    }

    /**
     * 开启数据库
     */
    private boolean dbEnable = false;
    public final void startDbThread() {
        if (this.dbEnable) {
            return;
        }
        this.dbEnable = true;
        if (this.dbManger != null) {
            this.dbManger = null;
        }
        this.dbManger = new DBManger(this);
        this.dbManger.start();
    }

    public void setMessage(Message message){
        UIMessenger = message.replyTo;
        boolean hasNetWork = Utils.isNetworkConnected(this);
        if(!hasNetWork){
            netUnAvailable();
        }
    }

}
